<template>
  <section>
    <!-- 面包屑 -->
      <breadcrumbs></breadcrumbs>
    <!-- <btns @exec="exec"></btns> -->
    <div class="data-container scroll-table">
      <div>
        <el-button @click="showCourseContentForm(1)">新增</el-button>
        <el-button @click="showCourseContentForm(2)">编辑</el-button>
        <el-button @click="del">删除</el-button>
        <el-button @click="enable">启用</el-button>
        <el-button @click="disable">禁用</el-button>
      </div>
      <div class="flex">
        <div class="ind-title lh50 f16">课程内容列表</div>
        <el-button type="primary" @click="returnCourseList">返回课程管理列表</el-button>
      </div>
      <el-table :data="tableData" @selection-change="tableSelectionChange" style="width: 100%" row-key="ifId" border lazy>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" prop="index" type="index" width="100px"></el-table-column>
        <el-table-column prop="title" label="课程内容标题" align="center"> </el-table-column>
        <el-table-column prop="" label="封面" width="80" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.headImg" alt="" class="img-feng">
          </template>
        </el-table-column>
        <el-table-column prop="" label="类型" align="center">
          <template slot-scope="scope">
            <p v-if="scope.row.type==1">直播</p>
            <p v-if="scope.row.type==2">视频</p>
            <p v-if="scope.row.type==3">课件</p>
          </template>
        </el-table-column>
        <el-table-column prop="" label="视频时长(秒)" align="center">
          <template slot-scope="scope">
            <p>{{scope.row.duration/1000}}</p>
          </template>
        </el-table-column>
        <el-table-column prop="" label="状态" align="center">
          <template slot-scope="scope">
            <p v-if="scope.row.state==1">启用</p>
            <p v-if="scope.row.state==2">禁用</p>
          </template>
        </el-table-column>
        <el-table-column prop="addtime" label="添加时间" align="center"> </el-table-column>
      </el-table>
      <!-- <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15, 20]"
                     :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination> -->
    </div>
    <el-dialog title="课程内容信息" :visible.sync="dialogCreateFormVisible">
      <el-form :model="createForm" label-width="120px" ref="createForm" :rules="rules">
        <el-form-item label="课程标题" prop="title">
          <el-input v-model="createForm.title" placeholder="请输入课程内容标题"></el-input>
        </el-form-item>
        <el-form-item label="课程类型" prop="Type">
          <el-select v-model="createForm.Type" placeholder="请选择课程内容类型">
            <el-option v-for="item in TypeList" :label="item.label" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程内容" prop="contentUrl">
          <!-- :on-preview="handlePreview" -->
          <el-upload class="upload-demo" :action="importFileUrl" v-model="createForm.contentUrl" :on-success="getUrl" :on-remove="handleRemove"
                     :before-remove="beforeRemove" multiple :file-list="fileList" ref='uploadDemo' :on-exceed="handleExceed">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">可上传课程视频或课件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="课程内容封面" prop="headImgUrl">
          <el-upload :action="importFileUrl" v-model="createForm.headImgUrl" list-type="picture-card" :before-upload="beforeAvatarUpload" :auto-upload="true"
                     :on-success="getHeadImgUrl" :accept="'image/*'" :show-file-list="false">
            <img v-if="hasFile" :src="headImgUrl" class="img-feng" alt="图片" />
            <i v-else class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="createForm.Type==2" label="时长" prop="videoNum">
          <el-input v-model="createForm.videoNum" type="number" placeholder="请输入时长(秒)"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="Sort">
          <el-input v-model="createForm.Sort" type="number" placeholder="请输入排序序号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearAdd">取 消</el-button>
        <el-button type="primary" @click="addContent('createForm')">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<style>
</style>
<script>


import btns from "@/components/btns.vue";
import breadcrumbs from "@/components/breadcrumbs.vue";
export default {
  components: {
    btns,
    breadcrumbs,

  },
  data() {
    return {
      importFileUrl: this.GLOBAL.imgBaseUrl,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      formType: "add",
      tableData: [],
      fileList: [],
      id: null,
      createForm: {},
      dialogCreateFormVisible: false,
      hasFile: false,
      headImgUrl: "",
      TypeList: [
        { id: 2, label: "视频" },
        { id: 3, label: "课件" },
      ],
      rules: {
        headImgUrl: [
          { required: true, message: "请选择课程内容封面", trigger: "change" },
          // { validator: allNumValidate, trigger: 'blur' }
        ],
        contentUrl: [
          { required: true, message: "请上传课程内容", trigger: "change" },
          // { validator: allNumValidate, trigger: 'blur' }
        ],

        videoNum: [
          { required: true, message: "请输入课程视频时长", trigger: "blur" },
          // { validator: allNumValidate, trigger: 'blur' }
        ],
        Sort: [
          { required: true, message: "请输入排序序号", trigger: "blur" },
          // { validator: allNumValidate, trigger: 'blur' }
        ],
        title: [
          { required: true, message: "请输入课程内容标题", trigger: "blur" },
          // { validator: allNumValidate, trigger: 'blur' }
        ],
        Type: [
          { required: true, message: "请选择课程内容类型", trigger: "change" },
          // { validator: allNumValidate, trigger: 'blur' }
        ],


      },
      tableSelection: [],
    };
  },

  created() {
    this.id = this.$route.query.id;
    console.log(this.id)
    this.getList(this.id);

  },
  methods: {
    del() {
      if (this.tableSelection.length < 1) {
        this.$message.error('请选中一行数据');
        return
      }
      this.$confirm("确认要删除这条消息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let ids = this.tableSelection.map(e => {
            return e.contentId
          })
          this.$api.course
            .delCourseContent({
              contentIds: ids.join(','),
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message({
                  type: "success",
                  message: "删除成功",
                });
                this.getList(this.id);
              } else {
                this.$message.error(d.msg);
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消");
        });
    },
    //启用
    enable() {
      if (this.tableSelection.length < 1) {
        this.$message.error("请选择要操作的数据！");
        return;
      }
      let ids = this.tableSelection.map((e) => {
        return e.state;
      });
      let contentId = this.tableSelection.map((e) => {
        return e.contentId;
      });
      let s = new Set(ids);
      if ([...s].length != 1) {
        return this.$message.error("请选择状态一致的数据！");
      }
      if ([...s][0] != 2) {
        return this.$message.error("请选择状态为禁用数据！");
      }
      this.$confirm("确认要启用这个课程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.course
            .enableCourseContent({
              contentIds: contentId.join(","),
              state: 1, //状态 2禁用 1启用
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message({
                  type: "success",
                  message: "启用成功",
                });
                this.getList(this.id);
              } else {
                this.$message.error(d.msg);
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消启用");
        });
    },
    //禁用
    disable() {
      if (this.tableSelection.length < 1) {
        this.$message.error("请选择要操作的数据！");
        return;
      }
      let ids = this.tableSelection.map((e) => {
        return e.state;
      });
      let contentId = this.tableSelection.map((e) => {
        return e.contentId;
      });
      let s = new Set(ids);
      if ([...s].length != 1) {
        return this.$message.error("请选择状态一致的数据！");
      }
      if ([...s][0] != 1) {
        return this.$message.error("请选择状态为启用数据！");
      }
      this.$confirm("确认要禁用这个课程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.course
            .enableCourseContent({
              contentIds: contentId.join(","),
              state: 2, //状态 2禁用 1启用
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message({
                  type: "success",
                  message: "禁用成功",
                });
                this.getList(this.id);
              } else {
                this.$message.error(d.msg);
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消禁用");
        });
    },
    clearAdd() {
      this.createForm = {},
        this.headImgUrl = "",
        this.hasFile = false;
      this.$refs.uploadDemo.clearFiles()
      this.dialogCreateFormVisible = false;
    },
    addContent(formName) {
      // console.log(this.createForm, "1------------------")
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formType == "add") {
            let row = this.createForm;
            this.$api.course.addCourseContent({
              content: row.contentUrl,
              courseId: this.id,
              duration: row.videoNum,
              headImg: row.headImgUrl,
              sort: row.Sort,
              title: row.title,
              type: row.Type
            }).then((res) => {
              if (res.code == 200) {
                this.clearAdd()
                this.$message.success("添加成功")
                this.getList(this.id)
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            let row = this.createForm;
            this.$api.course.editCourseContent({
              contentId: row.contentId,
              content: row.contentUrl,
              courseId: this.id,
              duration: row.videoNum * 1000,
              headImg: row.headImgUrl,
              sort: row.Sort,
              title: row.title,
              type: row.Type
            }).then((res) => {
              if (res.code == 200) {
                this.createForm = {},
                  this.headImgUrl = "",
                  this.hasFile = false;
                this.dialogCreateFormVisible = false;
                this.$message.success("修改成功")
                this.getList(this.id)
              }
            })
          }

        }
      })
    },
    beforeAvatarUpload() { },
    getUrl(data) {
      console.log(data);
      this.createForm.contentUrl = data;
    },
    getHeadImgUrl(data) {
      this.hasFile = true;
      this.headImgUrl = data;
      this.createForm.headImgUrl = data;
    },
    beforeRemove() { },
    handleRemove() { },
    // handlePreview() { },
    handleExceed() { },
    showCourseContentForm(index) {
      if (index == 1) {
        this.dialogCreateFormVisible = true;
      } else {
        this.formType = "edit"
        if (this.tableSelection.length != 1) {
          this.$message.error('请选中一行数据');
          return
        }
        var demo = this.tableSelection[0];
        console.log(demo);

        // contentId: row.contentId,
        //       content: row.contentUrl,
        //       courseId: this.id,
        //       duration: row.videoNum * 1000,
        //       headImg: row.headImgUrl,
        //       sort: row.Sort,
        //       title: row.title,
        //       type: row.Type
        this.createForm = {
          contentUrl: demo.content,
          videoNum: demo.duration / 1000,
          Sort: demo.sort,
          title: demo.title,
          Type: demo.type,
          contentId: demo.contentId,
          headImgUrl: demo.headImg,



        }
        this.dialogCreateFormVisible = true;
      }

    },
    returnCourseList() {
      this.$router.push("/class/list")
    },
    tableSelectionChange(val) {
      this.tableSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList(this.currentPage, val);
      // eslint-disable-next-line no-console
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList(val, this.pageSize);
      // eslint-disable-next-line no-console
      // console.log(`当前页: ${val}`);
    },

    getList(id) {
      this.$api.course.getCourseContentList({
        courseId: id
      })
        .then((d) => {
          if (d.code == 200) {
            this.tableData = d.data;
            this.total = d.totalCount;

          }
        });
    }
  },


};
</script>
<style lang="less" scoped>
.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.img-feng {
  width: 120px;
  height: 120px;
}
</style>
